package com.test40_JDBC;

import com.test40_JDBC.util.JDBCUtil;
import org.junit.Test;

import java.sql.Connection;
import java.sql.Statement;
import java.util.Arrays;

/**
 * 事务控制
 * 事务的四个特性：原子性、一致性、隔离性/独立性、持久性
 */
public class Demo05_Transaction {

    /**
     * JDBC连接采用自动事务处理模式：自动提交更新
     */
    @Test
    public void test1() throws Exception {
        Connection conn = JDBCUtil.getConnection();
        Statement statement = conn.createStatement();
        statement.addBatch("INSERT INTO user (name) VALUES ('李兴华 - A')");
        statement.addBatch("INSERT INTO user (name) VALUES ('李兴华 - B')");
        statement.addBatch("INSERT INTO user (name) VALUES ('李兴华 - 'C')");
        statement.addBatch("INSERT INTO user (name) VALUES ('李兴华 - D')");
        statement.addBatch("INSERT INTO user (name) VALUES ('李兴华 - E')");
        int[] result = statement.executeBatch();
        System.out.println("【批处理的执行结果】" + Arrays.toString(result));
        JDBCUtil.closeConnection(conn);
    }

    /**
     * 手工事务控制
     */
    @Test
    public void test2() throws Exception {
        Connection conn = JDBCUtil.getConnection();
        conn.setAutoCommit(false);  // 取消自动提交
        Statement statement = conn.createStatement();
        try {
            statement.addBatch("INSERT INTO user (name) VALUES ('李兴华 - A')");
            statement.addBatch("INSERT INTO user (name) VALUES ('李兴华 - B')");
            statement.addBatch("INSERT INTO user (name) VALUES ('李兴华 - 'C')");
            statement.addBatch("INSERT INTO user (name) VALUES ('李兴华 - D')");
            statement.addBatch("INSERT INTO user (name) VALUES ('李兴华 - E')");
            int[] result = statement.executeBatch();
            System.out.println("【批处理的执行结果】" + Arrays.toString(result));
            conn.commit();  // 没有异常，进行事务更新提交
        } catch (Exception e) {
            e.printStackTrace();
            conn.rollback();    // 回滚事务
        } finally {
            JDBCUtil.closeConnection(conn);
        }
    }
}
